<!--
 * @Description: 
 * @Author: william
 * @Date: 2025-06-17 11:27:18
 * @LastEditors: william
 * @LastEditTime: 2025-08-21 13:42:42
-->
<template>
  <CustomModal
    title="添加菜谱"
    v-model="visible"
    isTabbar
    :showCancelButton="false"
    :showConfirmButton="false"
  >
    <view class="modal-content">
      <view v-if="updateStatus === '0'" class="container">
        <nw-Button
          icon="download"
          text="平台下载"
          class="nw-button-download"
          @click="handlePlatDownload"
        ></nw-Button>
        <nw-Button
          icon="plus"
          text="手动添加"
          class="nw-button-plus"
          @click="handleManuallyAdd"
        ></nw-Button>
      </view>
      <view v-if="updateStatus === '1'" class="container">
        <image
          :src="getViteImageUrl('recipe/loading.png')"
          mode="aspectFit"
          class="icon update-icon"
        />
        <view class="content-text">正在下载更新本地菜谱数据库......</view>
      </view>
      <view v-if="updateStatus === '2'" class="container">
        <image
          :src="getViteImageUrl('recipe/downloaded.png')"
          mode="aspectFit"
          class="icon"
        />
        <view class="content-text">已下载更新本地菜谱数据库！</view>
      </view>
    </view>
    <up-toast ref="uToastRef" />
  </CustomModal>
</template>

<script setup>
defineOptions({
  name: 'UpdateRecipe',
  inheritAttrs: false
})

const visible = defineModel({
  type: Boolean,
  default: false
})
const emit = defineEmits(['confirm'])

// 数据缓存
const { userInfo } = storeToRefs(useUserStore())
const { recipeLibraryList } = storeToRefs(useRecipeStore())
const updateStatus = ref('0') // 0-未开始 1-下载中 2-下载完成 3-下载失败
const uToastRef = ref(null)

onMounted(_ => {
  //
})

const handlePlatDownload = _ => {
  console.log('handlePlatDownload')
  updateStatus.value = '1'
  g_api.recipe
    .apiDownloadRecipeInfo({
      tenantId: userInfo.value.tenantId,
      appId: g_utils.getAppId()
    })
    .then(({ code, data }) => {
      if (code === 200 && data) {
        recipeDataDeal(data)
        if (!data.length) {
          uToastRef.value.show({
            type: 'error',
            message: '无菜谱，请手动添加'
          })
        }
      } else {
        updateStatus.value = '0'
      }
    })
    .catch(err => {
      updateStatus.value = '0'
    })
    .finally(_ => {})
}

const recipeDataDeal = data => {
  // 1. 数据清洗（去重id + 格式化）
  let dataList = g_.cloneDeep(recipeLibraryList.value)
  const ids = new Set(dataList.map(item => item.id))
  // 替换本地存在的菜谱数据, 只替换线上更新时间较新的数据
  dataList = dataList.map(item => {
    const matchedItem = data.find(dataItem => dataItem.id === item.id && dataItem.updateTime > item.updateTime)
    return matchedItem
      ? g_i.apiDataFormat(matchedItem, g_i.recipe.downloadRecipeInfo)
      : item
  })
  // 筛选出云端中未在现有菜谱列表中的新菜谱
  const filterData = data.reduce((prev, curr) => {
    if (!ids.has(curr.id)) {
      prev.push(g_i.apiDataFormat(curr, g_i.recipe.downloadRecipeInfo))
    }
    return prev
  }, [])
  const newData = [...dataList, ...filterData]
  console.log('清洗后的新数据', newData)

  // 2. 并行图片转换 + 数据合并
  Promise.allSettled(newData.map(item => g_utils.urlToBase64(item.picturePath)))
    .then(res => {
      console.log('转换后的图像base64', res)
      res.forEach((item, i) => {
        if (item.status === 'fulfilled') {
          // console.log(`第 ${i + 1} 个成功:`, item.value)
          newData[i].picturePath = item.value
          newData[i].base64Image = item.value
        }
        // console.error(`第 ${i + 1} 个失败:`, item.reason)
      })
      recipeLibraryList.value = newData
      console.log('合并后的数据', recipeLibraryList.value)
      updateStatus.value = '2'
    })
    .catch(err => {
      console.error(err)
      updateStatus.value = '0'
    })
}

const handleManuallyAdd = _ => {
  console.log('handleManuallyAdd')
  visible.value = false
  uni.navigateTo({
    url: `/pages/recipe/detail?type=add`
  })
}
</script>

<style lang="scss" scoped>
.modal-content {
  display: flex;
  flex-direction: column;
  margin: 82rpx 0 42rpx;
}

.container {
  display: flex;
  flex-direction: column;
  padding: 0 26rpx;
  :deep(.nw-button) {
    flex: 1;
    height: 54rpx;
    border-radius: 28rpx;
    .u-button__text {
      font-size: 24rpx !important;
    }
    .u-icon__icon {
      margin-right: 20rpx !important;
      color: var(--color-fff) !important;
    }
    &:not(.u-button--disabled) .u-button__text {
      color: var(--color-fff);
    }
  }
  :deep(.nw-button-download) {
    .u-icon__icon {
      line-height: 26rpx !important;
      font-size: 26rpx !important;
    }
  }
  :deep(.nw-button-plus) {
    margin-top: 28rpx;
    .u-icon__icon {
      line-height: 22rpx !important;
      font-size: 22rpx !important;
    }
  }
  .icon {
    width: 86rpx;
    height: 86rpx;
    margin: 0 auto;
    &.update-icon {
      animation: spin 2s linear infinite;
    }
  }

  @keyframes spin {
    from {
      transform: rotate(0deg);
    }
    to {
      transform: rotate(360deg);
    }
  }

  .content-text {
    margin: 52rpx 0 0;
    line-height: 26rpx;
    text-align: center;
    font-size: 26rpx;
    font-weight: 400;
    color: var(--color-333);
  }
}
</style>
